package com.terry.client;

import java.util.List;

import com.terry.handler.HttpClientHandler;
import com.terry.interfaces.Contant;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpResponseDecoder;

public class NettyClient {

	private String host;
	private int port;
	
	public static void main(String[] args) {
		int port = Contant.TARGET_PORT;
		String host = Contant.TARGET_HOST;
		new NettyClient(host, port).run(null, null);
	}
	
	public void run(final ChannelHandlerContext ctx, final List<ByteBuf> msg) {
		final EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(workerGroup)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.SO_KEEPALIVE, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					//普通的消息发送
//					ch.pipeline().addLast(new MessageCoder());
//					ch.pipeline().addLast(new ClientHandler(workerGroup));
					//http消息
//					ch.pipeline().addLast(new HttpRequestDecoder());
					ch.pipeline().addLast(new HttpResponseDecoder());
					HttpClientHandler hch = new HttpClientHandler();
					hch.setServerChannelHandlerContext(ctx);
					hch.setRequestBody(msg);
					ch.pipeline().addLast(hch);
				}
			});
			ChannelFuture f = bootstrap.connect(host, port).sync();
//			f.addListener(new ChannelFutureListener() {
//				@Override
//				public void operationComplete(ChannelFuture future) throws Exception {
//					System.out.println(future.isSuccess());
//				}
//			});
		} catch(Exception e) {
			e.printStackTrace();
		} 
		
	}
	public NettyClient(String host, int port) {
		this.host = host;
		this.port = port;
	}
	

}
